package com.zrb.mobile.register;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.mobile.ui.ClearEditTextEx.onTextCorrectListener;
import com.zrb.mobile.ui.ClearPhoneEditText;
import com.zrb.mobile.ui.fragment.NotifyFragment;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegPhoneFragment  extends NotifyFragment implements onTextCorrectListener, OnClickListener{

 
	ClearPhoneEditText editTextphone;
	EditText editTextCode;
	TextView mbtn_verifycode,mTitle;
	Button nextstep_btn;
	
 
    View rootView;
    boolean isShow=false;
  	private String phoneNum,oldphoneNum;
   	boolean isChangephone=false;
    	
 
  	private TextView phoneNumstr;
  	MyCount mc;
  	
  	 
  	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// return inflater.inflate(R.layout.u_center_registerstep1, null);

		View view = inflater.inflate(R.layout.register_phonenumber, container, false);
		rootView=view;
		initView();
		return view;
	}
	
	private void initView() {
 
 		editTextphone = (ClearPhoneEditText) rootView.findViewById(R.id.layout_username);
		editTextphone.setOnTextCorrectListener(this);
 		
		editTextCode = (EditText) rootView.findViewById(R.id.edit_verifyCode);
  
		nextstep_btn=(Button)rootView.findViewById(R.id.nextbtn);
		nextstep_btn.setEnabled(false);
		nextstep_btn.setOnClickListener(this);
 	
		mbtn_verifycode=(TextView)rootView.findViewById(R.id.btn_validate_Code);
		mbtn_verifycode.setEnabled(false);
		mbtn_verifycode.setOnClickListener(this);
 	}
	

	/*定义一个倒计时的内部类*/  
    class MyCount extends CountDownTimer {     
        public MyCount(long millisInFuture, long countDownInterval) {     
            super(millisInFuture, countDownInterval);     
        }     
        @Override     
        public void onFinish() { 
        	mbtn_verifycode.setEnabled(true);
        	mbtn_verifycode.setText("获取验证码");        
        }     
        @Override     
        public void onTick(long millisUntilFinished) {     
        	mbtn_verifycode.setText("请等待(" + millisUntilFinished / 1000 + ")秒");     
           // Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有显示时间延迟       
        }    
    }     
    
  
    
   private boolean isPhoneOk(boolean isHite,boolean isSubmit){
   		
		if (this.editTextphone.isEmpty()) {
			if(isSubmit) initNotify("请输入正确的手机号");
			return false;
 		}
 		if(!CommonUtil.isMobileNO(this.editTextphone.getContentValue().replace(" ", "")))//CommonUtil.isMobileNO(this.editTextphone.getText()
		{
 			if(isHite) initNotify("请输入正确的手机号");
			return false;
		}
 		phoneNum=this.editTextphone.getContentValue().replace(" ", "");
		return true;
	}
   
   
	 private void checkPhone(){
	    	
	    	if(!isPhoneOk(true,true)) return ;
	    	RequestParams param = new RequestParams();
			param.put("mobile", phoneNum);
	 		ZrbRestClient.post("register/checkMobileRegister", param,
					new AsyncHttpResponseHandler() {
						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
	   						 initNotify(RegPhoneFragment.this.getString(R.string.error_net_loadfail));
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
	  					   String results = new String(arg2);
	  					   CommonUtil.InfoLog("checkMobileRegister", results);
							try {
								  Gson gson = new Gson();
								  RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
								  if(tmpDto.res == 1){
	 								getvalidateCode();
							      }
							      else{
							         initNotify(tmpDto.msg);
								  }
	 						   } catch (Exception e) {
	 							 initNotify(RegPhoneFragment.this.getString(R.string.error_serverdata_loadfail));
							}
						}
					});
	    }
	    
	 	private void getvalidateCode(){
	 		
	 		if(!isPhoneOk(true,true)) return ;
	 		RequestParams param = new RequestParams();
			param.put("mobile", phoneNum);
			 
			String requestUrl=isChangephone ?"user/sendModifyMobileAuthCode":"register/sendSMSRegister";
			if(isChangephone) 	param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
			ZrbRestClient.post(requestUrl, param,
					new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
	   						 initNotify(RegPhoneFragment.this.getString(R.string.error_net_loadfail));
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
	   					   String results = new String(arg2);
	 						try {
	 							Gson gson = new Gson();
	 							RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
	 							if(tmpDto.res==1){
	 								mbtn_verifycode.setEnabled(false);
	 								if(mc==null) mc = new MyCount(60000, 1000);  
	 						         mc.start();
	 							}
	 							else {
 	 								 initNotify(tmpDto.msg);
	 							}
	 						        
	  						 } catch (Exception e) {
	 							 initNotify(RegPhoneFragment.this.getString(R.string.error_serverdata_loadfail));
	 						}
	 					}
					});
		}
		
	 	private void showNextStep(String phone,String tmpCode){
	 		
	 		if(RegPhoneFragment.this.getActivity()==null) return;
	 		UserRegister.registerPhone=phone;
	 		UserRegister.tmpsmsCode=tmpCode;
	 		IShowNext tmp=(IShowNext)RegPhoneFragment.this.getActivity();
	 		tmp.showNextStep();
	 		
/*	 	   Intent it = new Intent(RegPhoneFragment.this.getActivity(), User_registername.class);
			   it.putExtra("phonenum", phoneNum);
			   it.putExtra("smscode",tmpCode);
		       startActivity(it);*/
		       
	 	}
	 	
		private void user_register() {
		 
			if (TextUtils.isEmpty(this.editTextCode.getText())) {
				initNotify("校验码不能为空");
				return;
			}
			if(!isPhoneOk(true,true)) return ;
	 		showloading("正在提交中..");
	  
			String url = String.format("%1$s?mobile=%2$s&smsCode=%3$s",
				            	isChangephone ? "user/updateAppUserPhone"
							                  : "register/checkSMSRegister", phoneNum,this.editTextCode.getText().toString());
	  		if(isChangephone)  url+="&zrb_front_ut="+AppSetting.curUser.zrb_front_ut;
	  		
	  		Log.e("url", url);
	 		ZrbRestClient.get(url, null,
					new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							// TODO Auto-generated method stub
							hideloading();
							initNotify(RegPhoneFragment.this.getString(R.string.error_net_loadfail));
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// TODO Auto-generated method stub
							hideloading();
							String results = new String(arg2);
							if(mc!=null) mc.cancel();
	 						try {
	 							Gson gson = new Gson();
	 							RegisterDto tmpDto = gson.fromJson(results,	RegisterDto.class);
	 							
	 							if(tmpDto.res==1){
	  								if(isChangephone){
	  									Intent data=new Intent();
	 									data.putExtra("phonenum", phoneNum);
	 									//User_registerphone.this.setResult(android.app.Activity.RESULT_OK, data);
	 									//User_registerphone.this.finish();
	 									CommonUtil.showToast("更改成功", RegPhoneFragment.this.getActivity());
	  							 
	 									return;
	 								}
	  								showNextStep(phoneNum,tmpDto.data);
 	 							}
	 							else 	
	 								initNotify(tmpDto.msg);

							} catch (Exception e) {
								initNotify(RegPhoneFragment.this.getString(R.string.error_serverdata_loadfail));
	 						}
	 					}
					});
	 	}

		@Override
		public void onTextCorrect(boolean isok) {
			// TODO Auto-generated method stub
			nextstep_btn.setEnabled(isok);
			mbtn_verifycode.setEnabled(isok);
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
  
			case R.id.nextbtn:
				user_register();
				break;
			case R.id.btn_validate_Code:
				//user_register();
 				checkPhone();
	 			break;
	 
	 		}
	 	}
	
	
	
}
